webix.ready(function(){
   var plans = JSON.parse($("#plans").val());
     var my_templaet={
        template: "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >生产产能</span>&nbsp;/&nbsp;&nbsp;ScheduleSheet",
        height:45,
        borderless:true 
    };
	var my_toolbar = {
			view : "toolbar",
			elements : [ {
				view : "combo",
				id : "plan_id",
				label : "选择计划",
				width : 260,
				labelWidth : 80,
				options : plans.data
			},  {
				view : "datepicker",
				id : "date",
				timepicker : true,
				label : "计划日期",
				labelAlign : "right",
				name : "end",
				stringResult : true,
				format : "%Y-%m-%d",
				width : 240
			}, {
				view : "button",
				value : "查询",
				width : 100,
				click : "select"
			} ,{
				id:"save",
				view : "button",
				value : "保存",
				width : 100,
				click : "save"
			} ,{
				id:"plan_desc",
				view:"label"
			} ]
		};
      var my_treetable={
        view:"datatable",
        id:"mytable",
        columns:[
             { id:"project_name",header:["项目名称",{ content:"textFilter", placeholder:"请输入项目名称进行查询",}],fillspace:true},
             { id:"project_id",header:"项目 id",hidden:true,fillspace:true},
             { id:"process_name",header:"工序",fillspace:true},
             { id:"process_id",header:"工序id",hidden:true,fillspace:true},
             { id:"class_id",header:"班别",hidden:true,fillspace:true},
             { id:"class_name",header:"班别",fillspace:true},
             { id:"yield",header:"计划产能",fillspace:true},
             { id:"actuaYield",header:"实际产能（单击填写）",fillspace:true,editor:"text"},
          ],
        height:700,
        editable:true,
		resizeColumn:true,
		tooltip:true,
        spans:true,
        select:"cell",
    };
     var body=new webix.ui({
        container:"body",
        type:"line",
        id:"mylayout",
        rows:[
              my_templaet,
              my_toolbar,
              my_treetable,
             
          ],// ----rows结束----
// ----rows结束----
    });// ---webix.ui结束----
});

function save(){
		  $$("save").disable();
		  $$("mytable").editStop();
		  var plan_id = $$("plan_id").getValue();
		  var date = $$("date").getValue().substr(0, 10);
		  var params = {};
		  var i=0;
		  var flag = true;
		 
		  var project_id = "";
		  
		  var plans = JSON.parse($("#plans").val());
		  if(plan_id == ""){
			  $$("save").enable();
				alert("请选择计划");
				return false;
		  }
			if(date == ""){
				$$("save").enable();
				alert("请选择时间");
				return false;
			}
			var d = new Date();
			var dt = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
			var date1 = new Date(dt.replace(/\-/g, "\/"));
			var date2 = new Date(date.replace(/\-/g, "\/"));
			var startDate = "";
			var endDate = "";
			
			if(Date.parse(date1)<Date.parse(date2)){
				$$("save").enable();
				alert("计划日期不能大于当天");
				return false;
			}
			
			for(var j=0;j<plans.data.length;j++){
				if(plans.data[j].plan_id == plan_id){
					 startDate = plans.data[j].plan_start_date;
					 endDate = plans.data[j].plan_end_date
					 break;
				}
			}
			var date3 = new Date(startDate.replace(/\-/g, "\/"));
			var date4 = new Date(endDate.replace(/\-/g, "\/"));
			
			if(Date.parse(date2) < Date.parse(date3) ){
				$$("save").enable();
				alert("计划日期不能小于计划时间："+startDate);
				return false;
			}
			if(Date.parse(date2) > Date.parse(date4)){
				$$("save").enable();
				alert("计划日期不能大于计划时间："+endDate);
				return false;
			}
			 var details = [];
			 
		  $$("mytable").eachRow(
				  function (row){
					  if(flag){
						  var item = $$("mytable").getItem(row);
						  if(item.actuaYield == "" || item.actuaYield == "0" || typeof(item.actuaYield) == "undefined"){
							  flag = false;
							  alert("第"+(i+1)+"行"+"实际产能 为空");
							  return;
						  }
						  
						  project_id = item.project_id;
						  details[i] = {
					    		  "actuaYield": item.actuaYield,
					    		  "yield": item.yield,
					    		  "classes_id": item.classes_id,
					    		  "classes_name": item.class_name,
					    		  "plan_id": item.plan_id,
					    		  "plan_name": item.plan_name,
					    		  "process_id": item.process_id,
					    		  "process_name": item.process_name,
					    		  "project_id": item.project_id,
					    		  "project_name": item.project_name,
					    		  "record_date": date,
						        };
						  i++;
					  }
					 
					  	// "gourp_names": item.actuaYield,
				  });
		  	if(details.length == 0){
		  		flag=false;
		  	} 
		  	
		  	if(flag){
		  		params.plan_id = plan_id;
		  		params.project_id = project_id;
		  		params.date = date;
		  		params.data = details;
				webix.ajax().sync().post("addProductionPlanActualYield", params, function(text, xml, xhr){
					
					var result=JSON.parse(text);
					if(result.ret==1){
						alert("执行完毕");
					}else{
						alert(result.msg);
					}
					select();
				  	$$("save").enable();
				});
		  	}
	  		$$("save").enable();
}

function select(){
	var params = {};
	
	var plan_id = $$("plan_id").getValue();
	var date = $$("date").getValue().substr(0, 10);
	var plans = JSON.parse($("#plans").val());
	params.plan_id = plan_id;
	params.date = date;
	if(plan_id == ""){
		alert("请选择计划");
		return false;
	}
	if(date == ""){
		alert("请选择时间");
		return false;
	}
	
	var d = new Date();
	var dt = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
	var date1 = new Date(dt.replace(/\-/g, "\/"));
	var date2 = new Date(date.replace(/\-/g, "\/"));
	var startDate = "";
	var endDate = "";
	
	
	if(Date.parse(date1)<Date.parse(date2)){
		alert("计划日期不能大于当天");
		return false;
	}
	
	for(var i=0;i<plans.data.length;i++){
		if(plans.data[i].plan_id == plan_id){
			 startDate = plans.data[i].plan_start_date;
			 endDate = plans.data[i].plan_end_date
			 break;
		}
	}
	var date3 = new Date(startDate.replace(/\-/g, "\/"));
	var date4 = new Date(endDate.replace(/\-/g, "\/"));
	
	if(Date.parse(date2) < Date.parse(date3) ){
		alert("计划日期不能小于计划时间："+startDate);
		return false;
	}
	if(Date.parse(date2) > Date.parse(date4)){
		alert("计划日期不能大于计划时间："+endDate);
		return false;
	}
	
	webix.ajax().sync().post("getPlanActualYieldList", params, function(text, xml, xhr){
		  var result=JSON.parse(text);
		  //console.log(JSON.stringify(result));
		  var plan=result.plan_data;
		  $("#plan_id").val(plan_id);
		  $("#use_date").val(date);
		  $("#is_auto").val(plan.is_auto);
		  var plan_str = "";
		 $$("plan_desc").define("label", plan_str);
		 $$('plan_desc').refresh();
 		 // var data = new webix.DataCollection({data:result.data});
		 // $$('mytable').data.sync(data);
		 $$('mytable').clearAll();
		 $$('mytable').define("data",result.data);
		 $$("mytable").refresh();
		 chuli(result.data);
    });
    
}	
	

// 对后台的数据进行分析，几个项目，几个工序
// 对后台的数据进行分析，几个项目，几个工序
function chuli(data){
  var d=data;
  // console.log(d);
  d.sort( function(a, b){   
    return (a["project_name"]) > (b["project_name"])? 1 : (a[ "project_name"]) == (b[ "project_name" ]) ? 0 : -1;   
  }); 
  var count=0;
  var arryNew1=Array();
  var arryNew2=Array();
  var arryNew3=Array();
  var temp="";
  var b1=Array();
  var b2=Array();
  var b3=Array();
  var b4=Array();
  var b5=Array();
  var b6=Array();
  var ddd=0;
  var ccc=0;
  var eee=0;
  var fff=0;
  var ggg=0;
  var hhh=0;
  
  for(var i=0;i<d.length;i++){
    // 得到项目重复情况
      if(b1[i]!=-1){
        temp=d[i].project_name;
        for(var j=0;j<d.length;j++){
          if(temp==d[j].project_name){
            count++;
            b1[j] = -1;
          }
        }
        arryNew1.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
        count = 0;// 让count的值重新等于0
      }
  }
  // 用于将数据排序得到调理好的数据
  var sortArray1=new Array();
  var sortArray2=new Array();
  var sortArray3=new Array();
  
  getSort(arryNew1,sortArray1,"process_name",d);
  for(var k=0;k<arryNew1.length;k++){
	  ccc=ddd+arryNew1[k];
	  for(var j=ddd;j<ccc;j++){
		  if(b2[j]!=-1){
			  temp=d[j].process_name;
			  for(var i=ddd;i<ccc;i++){
				  // 判断
				  if(temp==d[i].process_name){
					  count++;
					  b2[i] = -1;
				  }
			  } 
			  arryNew2.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
			  count = 0;// 让count的值重新等于0
		  }
	  }
	  ddd=ccc;
  }
  
  	$$('mytable').clearAll();
  	$$('mytable').define("data",d);
  	$$("mytable").refresh();
  	span(arryNew1,"project_name");
  	span(arryNew2, "process_name");
  	span(arryNew3, "classes_name");
  	span(arryNew3, "gourp_ids");
  	span(arryNew3, "actuaYield");
  	$$("mytable").refresh();
}

function span(arryNew1,key){
  var e1;
  var f1=0;
  var f11=0;
  for(var i=0;i<arryNew1.length;i++){
        f11=f1+f11;
        e1=$$("mytable").getIdByIndex(f11);
        $$("mytable").addSpan([
           [e1, key, 1, arryNew1[i]],
        ]);
        f1=arryNew1[i];
　　}
}
function getSort(arryNew2,sortArray2,key,d){
var p3=0;
var p4=0;
  for(var i=0;i<arryNew2.length;i++){
          sortArray2[i]=new Array();
          p3=p3+p4;
          for(var j=p3;j<p3+arryNew2[i];j++){
            sortArray2[i][j]=d[j];
          }
          sortArray2[i].sort( function(a, b){   
            return (a[key]) > (b[key])? 1 : (a[key]) == (b[key]) ? 0 : -1;  
          });
          var l=0;
          for(var k=p3;k<p3+arryNew2[i];k++){
            d[k]=sortArray2[i][l++];
          } 
          p4=arryNew2[i];
  　　}
}